var tls = require('tls'),
	fs = require('fs'),
	sys = require('sys'),
	http = require('http'),
	url = require('url');

var tlsPort  = process.argv[2],
	webPort  = process.argv[3],
	login    = process.argv[4],
	password = process.argv[5];

// Http Server
var server = http.createServer(function(req, res)
{
	sys.puts("Peer http server request.");	

	var queryData = url.parse(req.url, true).query;		

	var file = queryData.file;

	if(typeof file == 'undefined')
	{
		sys.puts("Missing parameter: file.");
		return;
	}

	sys.puts("File: " + file);

	var peer = require('./client');

	peer.upload(file, function (peers)
	{
		sys.puts("Received peers list: " + peers);

		peers = JSON.parse(peers);

	    fs.readFile(file, 'utf8', function (err, data)
		{	  
			if (err)
				return console.log(err);

			peers.forEach(function(item)
			{
				if(item.port == tlsPort)
					return;

				var peer = require('./peer-client');

				peer.sendFile(item.addredd, item.port, file, data);
			});
		});

		client.close();
	});

}).listen(webPort, function()
{
	sys.puts("Local http listing port: " + webPort);
});

var client = require('./client');

client.login(login, password, tlsPort, function(data)
{
	sys.puts("Returnin: " + data);

	//var peer = require('./peer-server');
	//peer.listen(tlsPort);
});

